﻿using DevExpress.XtraEditors;
using EkStudio.com.bean.xml.BillModule;
using EkStudio.com.bean.xml.BillReflect;
using EkStudio.com.bean.xml.reflection.JAXB;
using EkStudio.com.bean.xml.RootInterface;
using EkStudio.com.bean.xml.RootInterface.Field;
using EkStudio.com.common.unit;
using EkStudio.com.ui.form.Auto;
using EkStudio.com.ui.unitbill.property.Event;
using EkStudio.Com.UI.Interface;
using ScintillaNET;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace EkStudio.com.ui.form
{
    public partial class ReflectAutoSourceForm : XtraForm
    {

        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ReflectAutoSourceForm));

        private ProjectRootPanel RootPanel = null;
        private ProjectUnitBillInterface UnitPanel = null;

        private DataTable WhereData = null, OutData = null;

        private List<BillFormatModule> ModList = new List<BillFormatModule>();//引用模块列表
        private List<string> ModPathList = new List<string>();//选取的字段组列表

        private BillRefectDataNode Node = null;

        private BillModuleItem target = null,reflect = null;
        private string targetSheet = "";
        private string reflectSheet = "";

        private delegate void UpdateStatusDelegate(string key, string xml);

        public ReflectAutoSourceForm(BillReflectModuleItem _module, ProjectRootPanel root, ProjectUnitBillInterface unit, BillRefectDataNode node, BillModuleItem tag)
        {
            InitializeComponent();
            RootPanel = root;
            UnitPanel = unit;
            Node = node;
            target = tag;
            InitForm();
        }

        private void InitForm()
        {
            #region 初始化编辑器
            this.SqlEdit.Margins[0].Width = 20;
            this.SqlEdit.Margins[2].Type = MarginType.Symbol;
            this.SqlEdit.Margins[2].Mask = Marker.MaskFolders;
            this.SqlEdit.Margins[2].Sensitive = true;
            this.SqlEdit.Margins[2].Width = 20;

            SqlEdit.Markers[Marker.Folder].Symbol = MarkerSymbol.BoxPlus;
            SqlEdit.Markers[Marker.FolderOpen].Symbol = MarkerSymbol.BoxMinus;
            SqlEdit.Markers[Marker.FolderEnd].Symbol = MarkerSymbol.BoxPlusConnected;
            SqlEdit.Markers[Marker.FolderMidTail].Symbol = MarkerSymbol.TCorner;
            SqlEdit.Markers[Marker.FolderOpenMid].Symbol = MarkerSymbol.BoxMinusConnected;
            SqlEdit.Markers[Marker.FolderSub].Symbol = MarkerSymbol.VLine;
            SqlEdit.Markers[Marker.FolderTail].Symbol = MarkerSymbol.LCorner;

            SqlEdit.StyleResetDefault();
            SqlEdit.Styles[Style.Default].Font = "Consolas";
            SqlEdit.Styles[Style.Default].Size = 10;
            SqlEdit.StyleClearAll();


            // Configure the CPP (C#) lexer styles
            SqlEdit.Styles[Style.Cpp.Default].ForeColor = Color.Silver;
            SqlEdit.Styles[Style.Cpp.Comment].ForeColor = Color.FromArgb(0, 128, 0); // Green
            SqlEdit.Styles[Style.Cpp.CommentLine].ForeColor = Color.FromArgb(0, 128, 0); // Green
            SqlEdit.Styles[Style.Cpp.CommentLineDoc].ForeColor = Color.FromArgb(128, 128, 128); // Gray
            SqlEdit.Styles[Style.Cpp.Number].ForeColor = Color.Olive;
            SqlEdit.Styles[Style.Cpp.Word].ForeColor = Color.Blue;
            SqlEdit.Styles[Style.Cpp.Word2].ForeColor = Color.Blue;
            SqlEdit.Styles[Style.Cpp.String].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.Character].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.Verbatim].ForeColor = Color.FromArgb(163, 21, 21); // Red
            SqlEdit.Styles[Style.Cpp.StringEol].BackColor = Color.Pink;
            SqlEdit.Styles[Style.Cpp.Operator].ForeColor = Color.Purple;
            SqlEdit.Styles[Style.Cpp.Preprocessor].ForeColor = Color.Maroon;
            SqlEdit.Lexer = Lexer.Cpp;

            // Set the keywords
            //SqlEdit.SetKeywords(0, "abstract as base break case catch checked continue default delegate do else event explicit extern false finally fixed for foreach goto if implicit in interface internal is lock namespace new null object operator out override params private protected public readonly ref return sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe using virtual while");
            //SqlEdit.SetKeywords(1, "bool byte char class const decimal double enum float int long sbyte short static string struct uint ulong ushort void");

            SqlEdit.SetKeywords(0, common.unit.ULabel.SQLKeys);

            #endregion


            SqlEdit.Text = Node.Content;

            //初始化条件列
            WhereData = new DataTable("WhereData");
            WhereData.Columns.Add("ParamType", typeof(string));
            WhereData.Columns.Add("ParamKey", typeof(string));//sqlkey
            WhereData.Columns.Add("ParamValue",typeof(string));//caption
            WhereData.Columns.Add("ParamEqKey", typeof(string));//eqkey
            WhereData.Columns.Add("ParamEqType", typeof(string));
            WhereData.Columns.Add("ParamConst", typeof(string));
            WhereData.Columns.Add("ParamFrom", typeof(string));
            WhereData.Columns.Add("ParamFromKey", typeof(string));
            WhereGridControl.DataSource = WhereData;

            if (Node.RefectWhere == null) Node.RefectWhere = new BillRefectDataNodeWhereList();
            if (Node.RefectWhere.Item == null) Node.RefectWhere.Item = new List<BillRefectDataNodeWhereItem>();
            if (Node.RefectWhere.Item.Count > 0)
            {
                foreach(BillRefectDataNodeWhereItem it in Node.RefectWhere.Item)
                {
                    DataRow data = WhereData.NewRow();
                    data["ParamType"] = it.PType;
                    data["ParamKey"] = it.Key;
                    data["ParamValue"] = it.Caption;
                    data["ParamEqKey"] = it.Column;
                    data["ParamEqType"] = it.Eqmode;
                    data["ParamConst"] = it.ConstValue;
                    data["ParamFrom"] = it.ReflectCaption;
                    data["ParamFromKey"] = it.ReflectKey;
                    WhereData.Rows.Add(data);
                }
            }
            //输出设置
            OutData = new DataTable("OutData");
            OutData.Columns.Add("OutSource", typeof(string));
            OutData.Columns.Add("OutValCaption", typeof(string));
            OutData.Columns.Add("OutValColumn", typeof(string));
            OutData.Columns.Add("OutDateType", typeof(bool));
            OutGridControl.DataSource = OutData;
            if (Node.RefectValue == null) Node.RefectValue = new BillRefectDataNodeOutList();
            if (Node.RefectValue.Item == null) Node.RefectValue.Item = new List<BillRefectDataNodeOutItem>();
            if (Node.RefectValue.Item.Count > 0)
            {
                foreach(BillRefectDataNodeOutItem it in Node.RefectValue.Item)
                {
                    DataRow data = OutData.NewRow();
                    data["OutSource"] = it.Key;
                    data["OutValCaption"] = it.Caption;
                    data["OutValColumn"] = it.Column;
                    data["OutDateType"] = it.IsDate;
                    OutData.Rows.Add(data);
                }
            }

        }

        private void SubmitBtn_Click(object sender, EventArgs e)
        {
            Node.RefectWhere.Item.Clear();
            if (WhereData.Rows.Count > 0)
            {
                foreach(DataRow row in WhereData.Rows)
                {
                    BillRefectDataNodeWhereItem it = new BillRefectDataNodeWhereItem();
                    it.PType = (string)row["ParamType"];
                    it.Key = (string)row["ParamKey"];
                    it.Caption = (string)row["ParamValue"];
                    it.Column = (string)row["ParamEqKey"];
                    it.ConstValue = (string)row["ParamConst"];
                    it.Eqmode = (string)row["ParamEqType"];
                    it.ReflectKey = (string)row["ParamFromKey"];
                    it.ReflectCaption = (string)row["ParamFrom"];
                    Node.RefectWhere.Item.Add(it);
                }
            }
            Node.RefectValue.Item.Clear();
            if (OutData.Rows.Count > 0)
            {
                foreach(DataRow row in OutData.Rows)
                {
                    BillRefectDataNodeOutItem it = new BillRefectDataNodeOutItem();
                    it.Key = (string)row["OutSource"];
                    it.Caption = (string)row["OutValCaption"];
                    it.Column = (string)row["OutValColumn"];
                    it.IsDate = (bool)row["OutDateType"];
                    Node.RefectValue.Item.Add(it);
                }
            }
            Node.Content = SqlEdit.Text;
        }


        /// <summary>
        /// 参数格，参数值选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WhRepositoryParamValueEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                if (target != null)
                {
                    ModuleFieldSelectForm form = new ModuleFieldSelectForm();
                    if (targetSheet == "")
                    {
                        form.SetFormatBill(target, ModuleFieldSelectForm.ModuleLoadType.LoadTypeMain);
                    }
                    else
                    {
                        form.SetFormatBill(target, targetSheet);
                    }
                    if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        BillUiFieldsItem select = form.SelectField;
                        if (select != null)
                        {
                            DataRow data = WhereData.Rows[WhereGridView.FocusedRowHandle];
                            data["ParamValue"] = form.SelectPaths.Count > 0 ? form.SelectPaths[0] : "";
                            data["ParamEqKey"] = select.Key;
                            WhereGridView.RefreshRow(WhereGridView.FocusedRowHandle);
                        }
                    }
                }
                else
                {
                    XtraMessageBox.Show("目标为空");
                }
                
            }
            else if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                DataRow data = WhereData.Rows[WhereGridView.FocusedRowHandle];
                data["ParamValue"] = "";
                data["ParamEqKey"] = "";
                WhereGridView.RefreshRow(WhereGridView.FocusedRowHandle);
            }

        }

        private void WhRepositoryFromBut_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                if (reflect != null)
                {
                    ModuleFieldSelectForm form = new ModuleFieldSelectForm();
                    if (reflectSheet == "")
                    {
                        form.SetFormatBill(reflect, ModuleFieldSelectForm.ModuleLoadType.LoadTypeMain);
                    }
                    else
                    {
                        form.SetFormatBill(reflect, reflectSheet);
                    }
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        BillUiFieldsItem select = form.SelectField;
                        if (select != null)
                        {
                            DataRow data = WhereData.Rows[WhereGridView.FocusedRowHandle];
                            data["ParamFrom"] = form.SelectPaths.Count > 0 ? form.SelectPaths[0] : "";
                            data["ParamFromKey"] = select.Key;
                       
                            WhereGridView.RefreshRow(WhereGridView.FocusedRowHandle);
                        }
                    }
                }
                
            }
            else if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                DataRow data = WhereData.Rows[WhereGridView.FocusedRowHandle];
                data["ParamFrom"] = "";
                data["ParamFromKey"] = "";
                WhereGridView.RefreshRow(WhereGridView.FocusedRowHandle);
            }
        }

        /// <summary>
        /// 输出对象选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OutRepositoryFieldBut_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                ModuleFieldSelectForm form = new ModuleFieldSelectForm();
                if (targetSheet == "")
                {
                    form.SetFormatBill(target, ModuleFieldSelectForm.ModuleLoadType.LoadTypeMain);
                }
                else
                {
                    form.SetFormatBill(target, targetSheet);
                }
                if (form.ShowDialog() == DialogResult.OK)
                {
                    BillUiFieldsItem select = form.SelectField;
                    if (select != null)
                    {
                        DataRow data = OutData.Rows[OutGridView.FocusedRowHandle];
                        data["OutValCaption"] = form.SelectPaths.Count > 0 ? form.SelectPaths[0] : "";
                        data["OutValColumn"] = select.Key;
                        data["OutDateType"] = select.DataProperty.DataType == "dtDateTime";
                        OutGridView.RefreshRow(OutGridView.FocusedRowHandle);
                    }
                }
            }
            else if(e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Delete)
            {
                DataRow data = OutData.Rows[OutGridView.FocusedRowHandle];
                data["OutValCaption"] = "";
                data["OutValColumn"] = "";
                data["OutDateType"] = false;
                OutGridView.RefreshRow(OutGridView.FocusedRowHandle);
            }
        }



        #region *********************数据加载******************
        /// <summary>
        /// 加载服务器异步回调方法转界面线程 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoadXml(object sender, PropertyDataEvent e)
        {
            //异步转同步
            this.BeginInvoke(new UpdateStatusDelegate(LoadXmlToThreed), new object[] { e.Key, (string)e.Value });//LoadXmlToThreedReflect

        }

        private void LoadXmlReflect(object sender, PropertyDataEvent e)
        {
            //异步转同步
            this.BeginInvoke(new UpdateStatusDelegate(LoadXmlToThreedReflect), new object[] { e.Key, (string)e.Value });//LoadXmlToThreedReflect
        }

        #region 按钮功能集

        private void AutoSqlBtn_Click(object sender, EventArgs e)
        {
            if (UnitPanel.ReadOnly) return;
            if (target == null) return;
            AutoQueryFormula AutoQForm = new AutoQueryFormula(target, RootPanel);
            DialogResult DR = AutoQForm.ShowDialog();
            if (DR == DialogResult.OK)
            {
                //sql语句
                SqlEdit.Text = AutoQForm.SqlContent;
                //条件
                DataTable DataList = AutoQForm.ReqData;
                if (DataList.Rows.Count > 0)
                {
                    WhereData.Rows.Clear();
                    foreach (DataRow Row in DataList.Rows)
                    {
                        DataRow whRow = WhereData.NewRow();
                        whRow["ParamType"] = "变量";
                        whRow["ParamKey"] = Row["FieldParamKey"];
                        whRow["ParamValue"] = Row["FieldReqCaption"];
                        whRow["ParamEqKey"] = Row["FieldReqValue"];
                        whRow["ParamEqType"] = "=";
                        whRow["ParamConst"] = "";
                        whRow["ParamFrom"] = "";
                        whRow["ParamFromKey"] = "";
                        WhereData.Rows.Add(whRow);
                    }
                    WhereGridView.RefreshData();
                }
                //输出结果
                OutData.Rows.Clear();
                DataTable outTable = AutoQForm.OutData;
                if (outTable.Rows.Count > 0)
                {
                    foreach (DataRow data in outTable.Rows)
                    {
                        DataRow Row = OutData.NewRow();
                        //OutData.Columns.Add("OutSource", typeof(string));
                        //OutData.Columns.Add("OutValCaption", typeof(string));
                        //OutData.Columns.Add("OutValColumn", typeof(string));
                        //OutData.Columns.Add("OutDateType", typeof(bool));
                        if (data["ColFieldName"] is OutFieldData)
                        {
                            OutFieldData field = (OutFieldData)data["ColFieldName"];
                            Row["OutSource"] = field.Key;
                        }
                        else
                        {
                            Row["OutSource"] = "";
                        }
                        if (data["ColWriteField"] is OutFieldData)
                        {
                            OutFieldData outField = (OutFieldData)data["ColWriteField"];
                            Row["OutValCaption"] = outField.Caption;
                            Row["OutValColumn"] = outField.Key;
                            Row["OutDateType"] = false;
                        }
                        else
                        {
                            Row["OutValCaption"] = "";
                            Row["OutValColumn"] = "";
                            Row["OutDateType"] = false;
                        }
                        OutData.Rows.Add(Row);
                    }
                }
                OutGridView.RefreshData();
            }
        }

        /// <summary>
        /// 上移功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MoveUp_Click(object sender, EventArgs e)
        {
            if (target == null) return;
            if (UnitPanel.ReadOnly) return;
            if(SourceTabControl.SelectedTabPageIndex == 1)//条件框
            {
                int CHandleIndex = WhereGridView.FocusedRowHandle;
                if (CHandleIndex > 0)
                {
                    DataRow row = WhereData.Rows[CHandleIndex];
                    DataRow LastRow = WhereData.Rows[CHandleIndex - 1];
                    DataRow Tmp = WhereData.NewRow();
                    //data["ParamType"] = it.PType;
                    //data["ParamKey"] = it.Key;
                    //data["ParamValue"] = it.Caption;
                    //data["ParamEqKey"] = it.Column;
                    //data["ParamConst"] = it.ConstValue;
                    //data["ParamFrom"] = it.ReflectCaption;
                    //data["ParamFromKey"] = it.ReflectKey;
                    Tmp["ParamType"] = row["ParamType"];
                    Tmp["ParamKey"] = row["ParamKey"];
                    Tmp["ParamValue"] = row["ParamValue"];
                    Tmp["ParamEqKey"] = row["ParamEqKey"];
                    Tmp["ParamEqType"] = row["ParamEqType"];
                    Tmp["ParamConst"] = row["ParamConst"];
                    Tmp["ParamFrom"] = row["ParamFrom"];
                    Tmp["ParamFromKey"] = row["ParamFromKey"];

                    row["ParamType"] = LastRow["ParamType"];
                    row["ParamKey"] = LastRow["ParamKey"];
                    row["ParamValue"] = LastRow["ParamValue"];
                    row["ParamEqKey"] = LastRow["ParamEqKey"];
                    row["ParamEqType"] = LastRow["ParamEqType"];
                    row["ParamConst"] = LastRow["ParamConst"];
                    row["ParamFrom"] = LastRow["ParamFrom"];
                    row["ParamFromKey"] = LastRow["ParamFromKey"];

                    LastRow["ParamType"] = Tmp["ParamType"];
                    LastRow["ParamKey"] = Tmp["ParamKey"];
                    LastRow["ParamValue"] = Tmp["ParamValue"];
                    LastRow["ParamEqKey"] = Tmp["ParamEqKey"];
                    LastRow["ParamEqType"] = Tmp["ParamEqType"];
                    LastRow["ParamConst"] = Tmp["ParamConst"];
                    LastRow["ParamFrom"] = Tmp["ParamFrom"];
                    LastRow["ParamFromKey"] = Tmp["ParamFromKey"];


                    WhereGridView.RefreshRow(CHandleIndex - 1);
                    WhereGridView.RefreshRow(CHandleIndex);
                    //选中上一行
                    WhereGridView.MovePrev();
                }
            }
            else if(SourceTabControl.SelectedTabPageIndex == 2)//输出框
            {
                int CHandleIndex = OutGridView.FocusedRowHandle;
                if (CHandleIndex > 0)
                {
                    DataRow row = OutData.Rows[CHandleIndex];
                    DataRow LastRow = OutData.Rows[CHandleIndex - 1];
                    DataRow Tmp = OutData.NewRow();
                    //data["OutSource"] = it.Key;
                    //data["OutValCaption"] = it.Caption;
                    //data["OutValColumn"] = it.Column;
                    Tmp["OutSource"] = row["OutSource"];
                    Tmp["OutValCaption"] = row["OutValCaption"];
                    Tmp["OutValColumn"] = row["OutValColumn"];//Row["OutDateType"] = false;
                    Tmp["OutDateType"] = row["OutDateType"];

                    row["OutSource"] = LastRow["OutSource"];
                    row["OutValCaption"] = LastRow["OutValCaption"];
                    row["OutValColumn"] = LastRow["OutValColumn"];
                    row["OutDateType"] = LastRow["OutDateType"];

                    LastRow["OutSource"] = Tmp["OutSource"];
                    LastRow["OutValCaption"] = Tmp["OutValCaption"];
                    LastRow["OutValColumn"] = Tmp["OutValColumn"];
                    LastRow["OutDateType"] = Tmp["OutDateType"];

                    OutGridView.RefreshRow(CHandleIndex - 1);
                    OutGridView.RefreshRow(CHandleIndex);
                    //选中上一行
                    OutGridView.MovePrev();
                }
            }
        }
        /// <summary>
        /// 下移功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MoveDown_Click(object sender, EventArgs e)
        {
            if (target == null) return;
            if (UnitPanel.ReadOnly) return;
            if (SourceTabControl.SelectedTabPageIndex == 1)//条件框
            {
                int CHandleIndex = WhereGridView.FocusedRowHandle;
                if (CHandleIndex >=0 && CHandleIndex < WhereData.Rows.Count-1)
                {
                    DataRow row = WhereData.Rows[CHandleIndex];
                    DataRow LastRow = WhereData.Rows[CHandleIndex + 1];
                    DataRow Tmp = WhereData.NewRow();
                    //it.Key = (string)row["ParamKey"];
                    //it.Caption = (string)row["ParamValue"];
                    //it.Column = (string)row["ParamEqKey"];
                    Tmp["ParamType"] = row["ParamType"];
                    Tmp["ParamKey"] = row["ParamKey"];
                    Tmp["ParamValue"] = row["ParamValue"];
                    Tmp["ParamEqKey"] = row["ParamEqKey"];
                    Tmp["ParamEqType"] = row["ParamEqType"];
                    Tmp["ParamConst"] = row["ParamConst"];
                    Tmp["ParamFrom"] = row["ParamFrom"];
                    Tmp["ParamFromKey"] = row["ParamFromKey"];

                    row["ParamType"] = LastRow["ParamType"];
                    row["ParamKey"] = LastRow["ParamKey"];
                    row["ParamValue"] = LastRow["ParamValue"];
                    row["ParamEqKey"] = LastRow["ParamEqKey"];
                    row["ParamEqType"] = LastRow["ParamEqType"];
                    row["ParamConst"] = LastRow["ParamConst"];
                    row["ParamFrom"] = LastRow["ParamFrom"];
                    row["ParamFromKey"] = LastRow["ParamFromKey"];

                    LastRow["ParamType"] = Tmp["ParamType"];
                    LastRow["ParamKey"] = Tmp["ParamKey"];
                    LastRow["ParamValue"] = Tmp["ParamValue"];
                    LastRow["ParamEqKey"] = Tmp["ParamEqKey"];
                    LastRow["ParamEqType"] = Tmp["ParamEqType"];
                    LastRow["ParamConst"] = Tmp["ParamConst"];
                    LastRow["ParamFrom"] = Tmp["ParamFrom"];
                    LastRow["ParamFromKey"] = Tmp["ParamFromKey"];


                    WhereGridView.RefreshRow(CHandleIndex + 1);
                    WhereGridView.RefreshRow(CHandleIndex);
                    //选中上一行
                    WhereGridView.MoveNext();
                }
            }
            else if (SourceTabControl.SelectedTabPageIndex == 2)//输出框
            {
                int CHandleIndex = OutGridView.FocusedRowHandle;
                if (CHandleIndex >= 0 && CHandleIndex < OutData.Rows.Count - 1)
                {
                    DataRow row = OutData.Rows[CHandleIndex];
                    DataRow LastRow = OutData.Rows[CHandleIndex + 1];
                    DataRow Tmp = OutData.NewRow();
                    //data["OutSource"] = it.Key;
                    //data["OutValCaption"] = it.Caption;
                    //data["OutValColumn"] = it.Column;
                    Tmp["OutSource"] = row["OutSource"];
                    Tmp["OutValCaption"] = row["OutValCaption"];
                    Tmp["OutValColumn"] = row["OutValColumn"];//OutDateType
                    Tmp["OutDateType"] = row["OutDateType"];

                    row["OutSource"] = LastRow["OutSource"];
                    row["OutValCaption"] = LastRow["OutValCaption"];
                    row["OutValColumn"] = LastRow["OutValColumn"];
                    row["OutDateType"] = LastRow["OutDateType"];

                    LastRow["OutSource"] = Tmp["OutSource"];
                    LastRow["OutValCaption"] = Tmp["OutValCaption"];
                    LastRow["OutValColumn"] = Tmp["OutValColumn"];
                    LastRow["OutDateType"] = Tmp["OutDateType"];

                    OutGridView.RefreshRow(CHandleIndex + 1);
                    OutGridView.RefreshRow(CHandleIndex);
                    //选中上一行
                    OutGridView.MoveNext();
                }
            }
        }

        private void AddRow_Click(object sender, EventArgs e)
        {
            if (target == null) return;
            if (UnitPanel.ReadOnly) return;
            if(SourceTabControl.SelectedTabPageIndex == 1)
            {
                DataRow row = WhereData.NewRow();
                row["ParamType"] = "常量";
                row["ParamKey"] = "";
                row["ParamValue"] = "";
                row["ParamEqKey"] = "";
                row["ParamEqType"] = "=";
                row["ParamConst"] = "";
                row["ParamFrom"] = "";
                row["ParamFromKey"] = "";
                WhereData.Rows.Add(row);
                WhereGridView.RefreshData();
                WhereGridView.MoveLast();
            }
            else if(SourceTabControl.SelectedTabPageIndex == 2)
            {
                DataRow row = OutData.NewRow();
                row["OutSource"] = "";
                row["OutValCaption"] = "";
                row["OutValColumn"] = "";
                row["OutDateType"] = false;
                OutData.Rows.Add(row);
                OutGridView.RefreshData();
                OutGridView.MoveLast();
            }

        }

        private void DeleteRow_Click(object sender, EventArgs e)
        {
            if (target == null) return;
            if (UnitPanel.ReadOnly) return;
            if(SourceTabControl.SelectedTabPageIndex == 1)
            {
                int CHandleIndex = WhereGridView.FocusedRowHandle;
                if (CHandleIndex >= 0)
                {
                    WhereGridView.DeleteSelectedRows();
                    WhereGridView.MoveLast();
                }
            }
            else if(SourceTabControl.SelectedTabPageIndex == 2)
            {
                int CHandleIndex = OutGridView.FocusedRowHandle;
                if (CHandleIndex >= 0)
                {
                    OutGridView.DeleteSelectedRows();
                    OutGridView.MoveLast();
                }
            }
        }

        private void ReflectAutoSourceForm_Load(object sender, EventArgs e)
        {
            //加载模块
            if (Node.TargetKey != "" && target == null)
            {
                string modKey = "";
                string modCaption = "";
                if (Node.TargetKey.IndexOf(".") > 0)
                {
                    string[] list = Node.TargetKey.Split('.');
                    modKey = list[0];
                    modCaption = Node.TargetCaption.Split('.')[0].Replace("[", "").Replace("]", "");
                    if (list.Length > 1)
                    {
                        targetSheet = list[1];
                    }
                }
                else
                {
                    modKey = Node.TargetKey;
                    modCaption = Node.TargetCaption.Replace("[", "").Replace("]", "");
                    targetSheet = "";
                }
                if (modKey != "")
                {
                    bool ReadOnly = false;
                    RootPanel.Http.AsyncResourcesXmlBean(modKey, modCaption, ProjectUtil.TYPE_BILL_MODULE, ref ReadOnly, null, LoadXml);
                    LoadProgress.Visible = true;
                }
            }
            else //此处注意，目标http链接服务器，同时只能产生一个异步请求
            {
                //加载reflect
                if (Node.RefectKey != "" && reflect == null)
                {
                    string modKey = "";
                    string modCaption = "";
                    if (Node.RefectKey.IndexOf(".") > 0)
                    {
                        string[] list = Node.RefectKey.Split('.');
                        modKey = list[0];
                        modCaption = Node.RefectCaption.Split('.')[0].Replace("[", "").Replace("]", "");
                        if (list.Length > 1)
                        {
                            reflectSheet = list[1];
                        }
                    }
                    else
                    {
                        modKey = Node.RefectKey;
                        modCaption = Node.RefectCaption.Replace("[", "").Replace("]", "");
                        reflectSheet = "";
                    }
                    if (modKey != "")
                    {
                        bool ReadOnly = false;
                        RootPanel.Http.AsyncResourcesXmlBean(modKey, modCaption, ProjectUtil.TYPE_BILL_MODULE, ref ReadOnly, null, LoadXmlReflect);

                    }
                }
            }
            
        }

        private void SourceTabControl_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            InitParam();
        }


        private void InitParam()
        {
            #region 处理输出列表
            OutRepositoryFieldList.Items.Clear();
            string sql = SqlEdit.Text;
            if (sql.Length > 0)
            {
                sql = removeBracket(sql).ToLower();
                int index = sql.IndexOf("from");
                if (index != -1)
                {
                    sql = sql.Substring(0, index).Replace("select", "").Replace("\n", " ");
                    string[] keyList = sql.Split(',');
                    if (keyList.Length > 0)
                    {
                        for (int i = 0; i < keyList.Length; i++)
                        {
                            StringBuilder value = new StringBuilder();
                            string key = keyList[i].Trim();
                            int len = key.Length;
                            char ch = key[len - 1];
                            while (ch != ' ' && ch != '.' && len > 0)
                            {
                                value.Insert(0, ch);
                                len--;
                                if (len > 0) ch = key[len - 1];
                            }
                            OutRepositoryFieldList.Items.Add(value.ToString());
                        }
                    }
                }
            }
            #endregion
            #region 处理条件参数
            WhRepositoryParamKeyEdit.Items.Clear();
            sql = SqlEdit.Text;
            int ind = sql.IndexOf(":");
            while (ind > 0)
            {
                int begin = ind;
                int end = -1;
                StringBuilder value = new StringBuilder();

                for (int i = begin + 1; i < sql.Length; i++)
                {
                    if (!char.IsLetter(sql[i])&&sql[i]!='_')//非字母
                    {
                        end = i;
                        break;
                    }
                }
                if (end == -1)
                {
                    string str = sql.Substring(begin + 1).Trim();
                    WhRepositoryParamKeyEdit.Items.Add(str);
                    value.Append(sql.Substring(0, begin)).Append(" ");
                }
                else
                {
                    //"sssdsdfsdfsdfsdf"
                    int width = end - begin - 1;
                    string str = sql.Substring(begin + 1, width);
                    //logger.Info(string.Format("开始位置{0},结束位置[{1}],长度{2},字符[{3},取值[{4}]]",begin+1,end,width,sql,str));

                    WhRepositoryParamKeyEdit.Items.Add(str);
                    value.Append(sql.Substring(0, begin)).Append(" ");
                    value.Append(sql.Substring(end + 1));
                }
                sql = value.ToString();
                ind = sql.IndexOf(":");
            }
            #endregion
        }

        /// <summary>
        /// 去括号
        /// </summary>
        /// <param name="arg"></param>
        /// <returns></returns>
        private string removeBracket(string arg)
        {
            StringBuilder text = new StringBuilder();
            int index = arg.IndexOf("(");
            int timer = 20;
            while (index > 0 && timer > 0)
            {
                int begin = index;
                int end = -1;
                int Number = 0;
                text.Clear();
                for (int i = begin + 1; i < arg.Length; i++)
                {
                    char str = arg[i];
                    if (str == '(')
                    {
                        Number++;
                    }
                    else if (str == ')')
                    {
                        if (Number > 0)
                        {
                            Number--;
                        }
                        else
                        {
                            end = i;
                            break;
                        }
                    }
                }
                if (end != -1)
                {
                    text.Append(arg.Substring(0, begin)).Append(" ");
                    text.Append(arg.Substring(end + 1));
                }
                else
                {
                    text.Append(arg.Substring(0, begin));
                    text.Append(arg.Substring(begin + 1));
                }
                timer--;
                arg = text.ToString();
                index = arg.IndexOf("(");
            }

            return arg;
        }

        

        #endregion

        /// <summary>
        /// xml转bean target
        /// </summary>
        /// <param name="key"></param>
        /// <param name="xml"></param>
        private void LoadXmlToThreed(string key, string xml)
        {
            
            BillModuleItem loadBill = null;
            if (key == "OK")
            {
                
                XmlDocument XmlDoc = new XmlDocument();
                try
                {
                    XmlDoc.LoadXml(xml);
                    JAXBContext<BillModuleItem> jaxb = new JAXBContext<BillModuleItem>();
                    try
                    {
                        loadBill = jaxb.unmarshal(XmlDoc.OuterXml);
                    }
                    catch (Exception ex)
                    {
                        logger.Error("XMLTOBean失败", ex);
                        loadBill = null;
                    }

                }
                catch (Exception ex)
                {
                    logger.Error("返回Xml格式化失败:" + ex.Message, ex);
                    loadBill = null;
                }
            }
            if (loadBill != null)
            {
                target = loadBill;
                //加载reflect
                if (Node.RefectKey != "" && reflect == null)
                {
                    string modKey = "";
                    string modCaption = "";
                    if (Node.RefectKey.IndexOf(".") > 0)
                    {
                        string[] list = Node.RefectKey.Split('.');
                        modKey = list[0];
                        modCaption = Node.RefectCaption.Split('.')[0].Replace("[", "").Replace("]", "");
                        if (list.Length > 1)
                        {
                            reflectSheet = list[1];
                        }
                    }
                    else
                    {
                        modKey = Node.RefectKey;
                        modCaption = Node.RefectCaption.Replace("[", "").Replace("]", "");
                        reflectSheet = "";
                    }
                    if (modKey != "")
                    {
                        bool ReadOnly = false;
                        RootPanel.Http.AsyncResourcesXmlBean(modKey, modCaption, ProjectUtil.TYPE_BILL_MODULE, ref ReadOnly, null, LoadXmlReflect);
                        
                    }
                }
            }
            if (target == null) XtraMessageBox.Show("对象加载失败[" + Node.TargetCaption + "],请重新打开");
            
        }

        /// <summary>
        /// xml转bean target
        /// </summary>
        /// <param name="key"></param>
        /// <param name="xml"></param>
        private void LoadXmlToThreedReflect(string key, string xml)
        {

            BillModuleItem loadBill = null;
            if (key == "OK")
            {

                XmlDocument XmlDoc = new XmlDocument();
                try
                {
                    XmlDoc.LoadXml(xml);
                    JAXBContext<BillModuleItem> jaxb = new JAXBContext<BillModuleItem>();
                    try
                    {
                        loadBill = jaxb.unmarshal(XmlDoc.OuterXml);
                    }
                    catch (Exception ex)
                    {
                        logger.Error("XMLTOBean失败", ex);
                        loadBill = null;
                    }

                }
                catch (Exception ex)
                {
                    logger.Error("返回Xml格式化失败:" + ex.Message, ex);
                    loadBill = null;
                }
            }
            if (loadBill != null)
            {
                reflect = loadBill;
            }
            LoadProgress.Visible = false;
            if (reflect == null) XtraMessageBox.Show("对象加载失败[" + Node.RefectCaption + "],请重新打开");
        }
        #endregion
    }
}